package com.qixiaobao.common.websocket;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 * @author yangxm
 */
@Slf4j
@Component
@ServerEndpoint("/websocket/message/{userId}")
public class WebSocketServer {

    /**
     * 默认最多允许同时在线人数5000
     */
    public static int socketMaxOnlineCount = 5000;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws Exception {
        this.userId = userId;
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag) {
            // 未获取到信号量
            log.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        } else {
            // 添加用户
            WebSocketUsers.put(userId, session);
            log.info("\n 建立连接 - {}", session);
            log.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
            Map<String, Object> map = new HashMap<>();
            map.put("k","system");
            map.put("val","连接成功");
            WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(map));
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session) {
        log.info("\n 关闭连接 - {}", session);
        // 移除用户
        WebSocketUsers.remove(userId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        log.info("\n 连接异常 - {}", userId);
        log.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(userId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("当前用户：" + userId + "，消息：" + message);
        String msg = message.replace("你", "我").replace("吗", "");
        WebSocketUsers.sendMessageToUserByText(session, msg);
    }
}
